<?php

include_once 'BaseService.php';

class UserService extends BaseService {

	function auth($authCode) {
		global $_SGLOBAL;
		if (!$authCode) return false;

		$authCode = str_replace(' ', '+', $authCode);
		@list($password, $uid) = explode("\t", authcode(trim($authCode), 'DECODE'));
		$_SGLOBAL['supe_uid'] = intval($uid);
		if($_SGLOBAL['supe_uid']) {
			$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('session')." WHERE uid='$_SGLOBAL[supe_uid]' AND password='$password'");
			if($member = $_SGLOBAL['db']->fetch_array($query)) {
				$_SGLOBAL['supe_username'] = addslashes($member['username']);
				$_SGLOBAL['session'] = $member;
				return true;
			} else {
				$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('member')." WHERE uid='$_SGLOBAL[supe_uid]' AND password='$password'");
				if($member = $_SGLOBAL['db']->fetch_array($query)) {
					$_SGLOBAL['supe_username'] = addslashes($member['username']);
					include_once(S_ROOT.'./source/function_space.php');
					insertsession(array('uid' => $_SGLOBAL['supe_uid'], 'username' => $_SGLOBAL['supe_username'], 'password' => $password));//登录
					return $member;
				} else {
					return false;
				}
			}
		} else {
			return false;
		}
	}

	function getInfo($uId, $fields = array()) {
		global $_SGLOBAL;
		$result = array();
			$query = $_SGLOBAL['db']->query("SELECT sf.*, s.* FROM ".tname('space')." s
				LEFT JOIN ".tname('spacefield')." sf ON sf.uid=s.uid
				WHERE s.uid = '" . $uId . "'");
		$users = array();
		while($space = $_SGLOBAL['db']->fetch_array($query)) {
			$privacy = unserialize($space['privacy']);
			$users[$space['uid']] = array(
				'uid'		=> $space['uid'],
				'handle'	=> $space['username'],
				'action'	=> $space['action'],
				'realName'	=> $space['name'],
				'realNameChecked' => $space['namestatus'] ? true : false,
				'spaceName'	=> $space['spacename'],
				'gender'	=> $space['sex'] == 1 ? 'male' : ($space['sex'] == 2 ? 'female' : 'unknown'),
				'email'		=> $space['email'],
				'qq'		=> $space['qq'],
				'msn'		=> $space['msn'],
				'birthday'	=> sprintf('%04d-%02d-%02d', $space['birthyear'], $space['birthmonth'], $space['birthday']),
				'bloodType'	=> empty($space['blood']) ? 'unknown' : $space['blood'],
				'relationshipStatus' => $space['marry'] == 1 ? 'single' : ($space['marry'] == 2 ? 'notSingle' : 'unknown'),
				'birthProvince' => $space['birthprovince'],
				'birthCity'	=> $space['birthcity'],
				'resideProvince' => $space['resideprovince'],
				'resideCity'	=> $space['residecity'],
				'viewNum'	=> $space['viewnum'],
				'friendNum'	=> $space['friendnum'],
				'myStatus'	=> $space['note'],
				'lastActivity' => $space['updatetime'],
				'created'	=> $space['dateline'],
				'credit'	=> $space['credit'],
				'isUploadAvatar'	=> $space['avatar'] ? true : false,
				'homepagePrivacy'	=> $privacy['view']['index'] == 1 ? 'friends' : ($privacy['view']['index'] == 2 ? 'me' : 'public'),
				'profilePrivacy'	=> $privacy['view']['profile'] == 1 ? 'friends' : ($privacy['view']['profile'] == 2 ? 'me' : 'public'),
				'friendListPrivacy'	=> $privacy['view']['friend'] == 1 ? 'friends' : ($privacy['view']['friend'] == 2 ? 'me' : 'public'),
				'avatarMiddle' => UC_API . '/avatar.php?uid=' . $uId . '&size=middle&type=real',
				'avatarSmall' => UC_API . '/avatar.php?uid=' . $uId . '&size=small&type=real',
				'avatarBig' => UC_API . '/avatar.php?uid=' . $uId . '&size=big&type=real',
			);
		}
		return array_shift($users);
	}

	function login($username, $password) {
		global $_SGLOBAL;

		//同步获取用户源
		if(!$passport = getpassport($username, $password)) {
			$errCode = '1';
			$errMessage = 'Login Failed';
			//$this->sendFault($errCode, $errMessage);
			//exit;

			@header('Content-Type: text/xml');
			echo '<?xml version="1.0" encoding="utf-8"?>';
			echo '<methodResponse><fault><value><struct><member><name>faultCode</name><value><i4>';
			echo $errCoder;
			echo '</i4></value></member><member><name>faultString</name><value><string>';
			echo $errMessage;
			echo '</string></value></member></struct></value></fault></methodResponse>';
			exit();
		}

		$setarr = array(
			'uid' => $passport['uid'],
			'username' => addslashes($passport['username']),
			'password' => md5("$passport[uid]|$_SGLOBAL[timestamp]")//本地密码随机生成
		);

		//检索当前用户
		$query = $_SGLOBAL['db']->query("SELECT password FROM ".tname('member')." WHERE uid='$setarr[uid]'");
		if($value = $_SGLOBAL['db']->fetch_array($query)) {
			$setarr['password'] = addslashes($value['password']);
		} else {
			//更新本地用户库
			inserttable('member', $setarr, 0, true);
		}

		//清理在线session
		insertsession($setarr);

		//设置返回参数
		$ret = array();
		$ret['authCode'] = authcode("$setarr[password]\t$setarr[uid]", 'ENCODE');
		$ret['loginUser'] = $passport['username'];
		$ret['uid'] = $passport['uid'];

		//同步登录
		include_once S_ROOT.'./uc_client/client.php';
		$ucsynlogin = uc_user_synlogin($setarr['uid']);

		return $ret;
	}

	function logout() {
		global $_SGLOBAL;

		if($_SGLOBAL['supe_uid']) {
			$_SGLOBAL['db']->query("DELETE FROM ".tname('session')." WHERE uid='$_SGLOBAL[supe_uid]'");
			$_SGLOBAL['db']->query("DELETE FROM ".tname('adminsession')." WHERE uid='$_SGLOBAL[supe_uid]'");//管理平台
		}

		include_once S_ROOT.'./uc_client/client.php';
		$ucsynlogout = uc_user_synlogout();
		return array(
			'code' => 1,
			'message' => 'Logout success'
			);
	}

}
